package com.wzu.rjgc_ks.controller;

import com.wzu.rjgc_ks.dao.EchartsMapper;
import com.wzu.rjgc_ks.dao.StudentMapper;
import com.wzu.rjgc_ks.pojo.Echarts;
import com.wzu.rjgc_ks.pojo.Student;
import com.wzu.rjgc_ks.utils.ExcelUtil;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
public class StuAdminDataAction {

    @Autowired
    StudentMapper studentMapper;
    @Autowired
    EchartsMapper echartsMapper;


    @RequestMapping("/getStudent")
    public List<Echarts> getStudent(){

        List<Echarts> list = echartsMapper.selectByEmployment();
        for(Echarts ect:list)
        {
            switch (ect.getName())
            {
                case "F0":
                    ect.setName("未就业女生");
                    break;
                case "F1":
                    ect.setName("就业女生");
                    break;
                case "M0":
                    ect.setName("未就业男生");
                    break;
                case "M1":
                    ect.setName("就业男生");
                    break;
            }
        }
        return list;
    }

    @RequestMapping("/getAddress")
    public List<Echarts> getAddress(){

        List<Echarts> list = echartsMapper.selectByIntentAddress();

        return list;
    }

    @RequestMapping("/getSalary")
    public List<Echarts> getSalary(){

        List<Echarts> list = echartsMapper.selectByIntentSalary();

        return list;
    }

    @RequestMapping("/getWork")
    @ResponseBody
    public List<Student> getWork(@RequestParam(value = "stuMajor") String stuMajor,
                                 @RequestParam(value = "stuGrade") String stuGrade){

        List<Student> list;
        if("".equals(stuMajor) && "".equals(stuGrade)){
            list = studentMapper.selectWorkList();
        }else {
            Student student = new Student();
            student.setStuMajor(stuMajor);
            student.setStuGrade(stuGrade);
            list= studentMapper.selectWorkByMajorList(stuMajor ,stuGrade);
        }

        return list;
    }

    @RequestMapping("/downWork")
    public void downWork(@RequestParam(value = "stuMajor") String stuMajor,
                                  @RequestParam(value = "stuGrade") String stuGrade,
                                  HttpServletResponse response)  throws Exception{

        List<Student> list;
        if("".equals(stuMajor) && "".equals(stuGrade)){
            list = studentMapper.selectWorkList();
        }else {
            Student student = new Student();
            student.setStuMajor(stuMajor);
            student.setStuGrade(stuGrade);
            list= studentMapper.selectWorkByMajorList(stuMajor ,stuGrade);
        }

        List files = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            File file = new File(list.get(i).getWork().getWorProof());
            files.add(file);
        }
        downLoadFiles(files, response);
    }

    @RequestMapping("/downWork2")
    public void downWork2(HttpServletResponse response)  throws Exception{

        List<Student> list;
        list = studentMapper.selectWorkList();

        List files = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            File file = new File(list.get(i).getWork().getWorProof());
            files.add(file);
        }
        downLoadFiles(files, response);
    }







    @RequestMapping("/down")
    public String down(HttpServletResponse response) throws Exception{

        List files = new ArrayList();

        File file1 = new File("D:\\123.xlsx");
        File file2 = new File("D:\\ajax.sql");

        files.add(file1);
        files.add(file2);
        downLoadFiles(files, response);

        return "成功";
    }

    @RequestMapping("/downOne/{id}")
    public String downOne(@PathVariable("id") Integer id, HttpServletResponse response) throws Exception{

        List files = new ArrayList();

        Student student = studentMapper.selectWorkListByPrimaryKey(id);

        File file1 = new File(student.getWork().getWorProof());
        System.out.println(student.getWork().getWorProof());
        files.add(file1);
        downLoadFiles(files, response);

        return "成功";
    }

    public static HttpServletResponse downLoadFiles(List<File> files, HttpServletResponse response) throws Exception {

        try {
            // List<File> 作为参数传进来，就是把多个文件的路径放到一个list里面
            // 创建一个临时压缩文件

            // 临时文件可以放在CDEF盘中，但不建议这么做，因为需要先设置磁盘的访问权限，最好是放在服务器上，方法最后有删除临时文件的步骤

            String zipFilename = "D:/tempFile.zip";
            File file = new File(zipFilename);
            file.createNewFile();
            if (!file.exists()) {
                file.createNewFile();
            }
            response.reset();
            // response.getWriter()
            // 创建文件输出流
            FileOutputStream fous = new FileOutputStream(file);
            ZipOutputStream zipOut = new ZipOutputStream(fous);
            zipFile(files, zipOut);
            zipOut.close();
            fous.close();
            return downloadZip(file, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 把接受的全部文件打成压缩包
     *
     */
    public static void zipFile(List files, ZipOutputStream outputStream) {
        int size = files.size();
        for (int i = 0; i < size; i++) {
            File file = (File) files.get(i);
            zipFile(file, outputStream);
        }
    }

    /**
     * 根据输入的文件与输出流对文件进行打包
     *
     */
    public static void zipFile(File inputFile, ZipOutputStream ouputStream) {
        try {
            if (inputFile.exists()) {
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 512);
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(entry);
                    // 向压缩文件中输出数据
                    int nNumber;
                    byte[] buffer = new byte[512];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    // 关闭创建的流对象
                    bins.close();
                    IN.close();
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
        if (file.exists() == false) {
            System.out.println("待压缩的文件目录：" + file + "不存在.");
        } else {
            try {
                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();

                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");

                // 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    File f = new File(file.getPath());
                    f.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return response;
    }

//    //导出
//    @RequestMapping("/exp")
//    public void export(HttpServletResponse response) throws Exception {
////        //模拟数据库数据
////        Goods goods1 = new Goods(110, "苹果", 1, new Date(), 0, "1");
////        Goods goods2 = new Goods(111, "格子衫", 2, new Date(), 0, "0");
////        Goods goods3 = new Goods(112, "拉菲红酒", 3, new Date(), 1, "1");
////        Goods goods4 = new Goods(113, "玫瑰", 4, new Date(), 1, "0");
////
////        List<Goods> goodsList = new ArrayList<Goods>();
////        goodsList.add(goods1);
////        goodsList.add(goods2);
////        goodsList.add(goods3);
////        goodsList.add(goods4);
////
////        for (Goods goods : goodsList) {
////            System.out.println(goods);
////        }
////        //导出
////        ExcelUtil.exportExcel(goodsList,Goods.class,"商品.xls",response);
//    }
//    //导入
//    @RequestMapping("/imp")
//    public void importExcel() throws Exception {
//        //本地文件 模拟文件上传解析
//        String filePath = "E:/学生表.xls";
//        //解析excel
//        List<Student> goodsList = ExcelUtil.importExcel(filePath,0,1,Student.class);
//        //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)导入
//        System.out.println("导入数据一共【"+goodsList.size()+"】行");
//
//        //TODO 保存数据库
//        for (Student goods:goodsList) {
//            System.out.println(goods);
//        }
//    }
}
